<template>
  <view class="login-container">
    <image class="bg-image" src="/static/images/login-bg.png" mode="aspectFill"></image>
    <view class="login-content">
      <view class="login-header">
        <text class="title">友知</text>
        <text class="subtitle">以技术为桥，遇知己于方寸之间</text>
      </view>

      <view class="login-form">
        <!-- 微信登录界面 -->
        <view v-if="!showPasswordLogin" class="wechat-login">
          <view class="welcome-text">
            <text class="welcome-desc">使用微信账号快速登录，享受更多功能</text>
          </view>

          <button
            class="auth-wrapper"
            open-type="getPhoneNumber"
            @getphonenumber="handleGetPhoneNumber"
          >
            <u-button
              class="wechat-login-btn"
              :loading="loading"
              type="success"
              size="large"
              shape="circle"
            >
              <u-icon name="weixin-fill" size="40" color="#fff" class="wechat-icon"></u-icon>
              <text class="btn-text">{{ loading ? '登录中...' : '微信一键登录' }}</text>
            </u-button>
          </button>

          <view class="divider">
            <view class="divider-line"></view>
            <text class="divider-text">或</text>
            <view class="divider-line"></view>
          </view>

          <u-button
            class="password-login-btn"
            type="primary"
            size="large"
            shape="circle"
            plain
            @click="switchToPasswordLogin"
          >
            <u-icon name="account-fill" size="40" color="#667eea" class="account-icon"></u-icon>
            <text class="btn-text">用户名密码登录</text>
          </u-button>
        </view>

        <!-- 用户名密码登录界面 -->
        <view v-else class="password-login">
          <view class="login-header-small">
            <text class="title-small">手机号登录</text>
            <text class="subtitle-small">请输入您的手机号和密码</text>
          </view>

          <view class="form-item">
            <text class="label">手机号</text>
            <input v-model="formData.phone" class="input" placeholder="请输入手机号" type="tel" />
          </view>

          <view class="form-item">
            <text class="label">密码</text>
            <input
              v-model="formData.password"
              class="input"
              placeholder="请输入密码"
              type="password"
            />
          </view>

          <u-button
            class="login-btn"
            :loading="loading"
            type="primary"
            size="large"
            shape="circle"
            @click="handlePasswordLogin"
          >
            <text class="btn-text">{{ loading ? '登录中...' : '登录' }}</text>
          </u-button>

          <view class="back-to-wechat">
            <text class="back-link" @click="switchToWechatLogin">返回微信登录</text>
          </view>
        </view>

        <view class="privacy-tips">
          <text class="tips-text">登录即表示同意</text>
          <text class="link-text" @click="showPrivacyPolicy">《用户协议》</text>
          <text class="tips-text">和</text>
          <text class="link-text" @click="showPrivacyPolicy">《隐私政策》</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref, reactive } from 'vue';
  import { UserService } from '@/services';
  import { post } from '@/utils/request';
  import IMSDK from 'openim-uniapp-polyfill';
  
  const loading = ref(false);
  const showPasswordLogin = ref(false);

  const formData = reactive({
    phone: '',
    password: '',
  });

  // 切换到用户名密码登录
  const switchToPasswordLogin = () => {
    showPasswordLogin.value = true;
  };

  // 切换到微信登录
  const switchToWechatLogin = () => {
    showPasswordLogin.value = false;
    // 清空表单数据
    formData.phone = '';
    formData.password = '';
  };

  // 处理手机号授权
  const onGetPhoneNumber = e => {
    console.log('点击了微信一键登录', e);
    loading.value = true;

    // 检查用户是否授权
    console.log('微信授权详情:', e.detail);
    console.log('授权状态:', e.detail.errMsg);
    console.log('手机号code:', e.detail.code);

    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      console.log('微信验证失败，错误信息:', e.detail.errMsg);
      console.log('错误代码:', e.detail.errno);
      let errorMsg = '微信验证失败';

      // 根据不同的错误类型提供具体提示
      if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
        errorMsg = '用户拒绝授权手机号';
      } else if (e.detail.errMsg === 'getPhoneNumber:fail no permission') {
        errorMsg = '小程序暂无手机号权限，请联系开发者配置';
      } else if (e.detail.errMsg === 'getPhoneNumber:fail') {
        // 检查具体的错误代码
        if (e.detail.errno === -13000) {
          errorMsg = '系统错误，请稍后重试';
        } else {
          errorMsg = '获取手机号失败，请重试';
        }
      } else if (e.detail.errMsg.includes('fail')) {
        errorMsg = '微信授权失败：' + e.detail.errMsg;
      }

      // 如果有错误代码，显示更详细的信息
      if (e.detail.errno) {
        errorMsg += ` (错误代码: ${e.detail.errno})`;
      }

      uni.showToast({ title: errorMsg, icon: 'none', duration: 3000 });
      loading.value = false;
      return;
    }

    // 检查是否获取到手机号code
    if (!e.detail.code) {
      console.log('未获取到手机号code');
      uni.showToast({ title: '未获取到手机号授权码，请重试', icon: 'none', duration: 3000 });
      loading.value = false;
      return;
    }

    console.log('微信验证成功，手机号code:', e.detail.code);

    uni.login({
      success: async loginRes => {
        console.log('获取到登录code:', loginRes.code);

        try {
          console.log('准备调用登录接口，参数:', {
            loginCode: loginRes.code,
            phoneCode: e.detail.code || '',
          });

          // 使用新的服务层架构，会自动处理登录状态和用户信息存储
          await UserService.wechatLogin(e.detail.code || '');

          // 登录成功，跳转到首页
          setTimeout(() => {
            uni.switchTab({ url: '/pages/match/index' });
          }, 1500);
        } catch (err) {
          console.error('登录接口调用失败:', err);
          loading.value = false;
          // 错误处理已在 UserService 中完成，这里只需要恢复 loading 状态
        }
      },
      fail(err) {
        console.error('获取登录code失败:', err);
        loading.value = false;
        uni.showToast({ title: '获取登录凭证失败', icon: 'none' });
      },
    });
  };

  // 为了保持兼容性，保留原函数名的引用
  const handleGetPhoneNumber = onGetPhoneNumber;

  // 用户名密码登录
  const handlePasswordLogin = async () => {
    // 表单验证
    if (!formData.phone.trim()) {
      uni.showToast({
        title: '请输入手机号',
        icon: 'none',
      });
      return;
    }

    if (!formData.password.trim()) {
      uni.showToast({
        title: '请输入密码',
        icon: 'none',
      });
      return;
    }

    loading.value = true;

    try {
      // 使用封装好的post方法
      const result = await post('/c/user/login', {
        phone: formData.phone,
        password: formData.password,
      });

      const token = result.data.token;

      // 直接处理返回的data
      if (result.code === 200) {
        // 登录成功
        uni.showToast({
          title: '登录成功',
          icon: 'success',
        });

        // 存储用户信息
        uni.setStorageSync('userInfo', result.data);
        uni.setStorageSync('token', token);

        const { imToken, token } = result.data;
        const { ID } = result.data.user; 
        console.log("imToken=",imToken, "uuid=",ID)
        uni.setStorageSync('userId', ID);
        await UserService.saveApiLoginInfo(token, result.data.user);
        await IMSDK.asyncApi('login', IMSDK.uuid(),{
          userID: ID,
          token: imToken
        }).then(() => {
          // 登录成功
          console.log("IMSDK 登录成功");
          uni.showToast({
            title: `IMSDK 登录成功`,
            icon: 'none',
          });
        }).catch((error) => {
          // 登录失败
          uni.showToast({
            title: `IMSDK 登录失败: ${error}`,
            icon: 'none',
          });
          console.log('IMSDK 登录失败:', error);
        });
        // IMSDK.getLoginStatus()
        //   .then(({ data }) => {
        //     // data: 登录状态LoginStatus
        //     console.log("IMSDK IM登陆后登录状态 = ", data);
        //   })
        //   .catch(({ errCode, errMsg }) => {
        //     // 调用失败
        //   });

        // 跳转到首页
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/match/index',
          });
        }, 1500);
      } else {
        console.log('登录失败，返回结果:', result);
        // 登录失败 - 显示具体错误信息
        uni.showToast({
          title: result.msg || '登录失败',
          icon: 'none',
        });
      }
    } catch (error) {
      console.error('登录错误:', error);
      uni.showToast({
        title: '登录失败，请重试',
        icon: 'none',
      });
    } finally {
      loading.value = false;
    }
  };

  // 显示隐私政策
  const showPrivacyPolicy = () => {
    uni.showModal({
      title: '用户协议与隐私政策',
      content: '我们承诺保护您的隐私安全，仅获取必要的用户信息用于服务提供。',
      showCancel: false,
      confirmText: '我知道了',
    });
  };
</script>

<style lang="scss" scoped>
  .login-container {
    height: 100vh;
    position: relative;
    overflow: hidden;

    .bg-image {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 1;
    }

    .login-content {
      position: relative;
      z-index: 2;
      height: 100vh;
      padding: 40rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
  }

  .login-header {
    text-align: center;
    margin-bottom: 80rpx;

    .title {
      font-size: 72rpx;
      color: #333333;
      /* 修改为深色 */
      font-weight: 900;
      letter-spacing: 8rpx;
      text-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
      /* 减轻阴影 */
      margin-bottom: 20rpx;
      display: block;
    }

    .subtitle {
      font-size: 32rpx;
      color: #555555;
      /* 修改为深色 */
      font-weight: 400;
      letter-spacing: 2rpx;
    }
  }

  .login-form {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20rpx);
    border-radius: 24rpx;
    padding: 60rpx 40rpx;
    box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
    border: 1rpx solid rgba(255, 255, 255, 0.2);
  }

  .welcome-text {
    text-align: center;
    margin-bottom: 60rpx;

    .welcome-desc {
      display: block;
      font-size: 28rpx;
      color: #7f8c8d;
      line-height: 1.6;
    }
  }

  .auth-wrapper {
    width: 100%;
    background: transparent;
    border: none !important;
    padding: 0;
    margin: 0;
    display: block;
    outline: none;
    box-shadow: none !important;
  }

  .auth-wrapper::after {
    border: none !important;
  }

  .wechat-login-btn {
    width: 100%;
    height: 96rpx;
    background: #07c160;
    color: #fff;
    border: none;
    border-radius: 16rpx;
    font-size: 34rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 40rpx;
    transition: all 0.3s ease;
    box-shadow: 0 8rpx 24rpx rgba(7, 193, 96, 0.3);

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.4);
    }

    &[loading] {
      opacity: 0.8;
      transform: none;
    }

    .wechat-icon {
      width: 40rpx;
      height: 40rpx;
      flex-shrink: 0;
    }

    .btn-text {
      font-size: 34rpx;
      font-weight: 600;
      flex-shrink: 0;
    }
  }

  .divider {
    display: flex;
    align-items: center;
    margin: 40rpx 0;

    .divider-line {
      flex: 1;
      height: 2rpx;
      background: #e8eaed;
    }

    .divider-text {
      margin: 0 20rpx;
      font-size: 24rpx;
      color: #7f8c8d;
    }
  }

  .password-login-btn {
    width: 100%;
    height: 96rpx;
    background: transparent;
    color: #667eea;
    border: 2rpx solid #667eea;
    border-radius: 16rpx;
    font-size: 34rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 40rpx;
    transition: all 0.3s ease;

    &:active {
      transform: translateY(2rpx);
      background: rgba(102, 126, 234, 0.1);
    }

    .account-icon {
      width: 40rpx;
      height: 40rpx;
      flex-shrink: 0;
    }

    .btn-text {
      font-size: 34rpx;
      font-weight: 600;
      flex-shrink: 0;
    }
  }

  .login-header-small {
    text-align: center;
    margin-bottom: 40rpx;

    .title-small {
      font-size: 36rpx;
      color: #2c3e50;
      font-weight: 700;
      margin-bottom: 12rpx;
      display: block;
    }

    .subtitle-small {
      font-size: 24rpx;
      color: #7f8c8d;
      font-weight: 400;
    }
  }

  .form-item {
    margin-bottom: 40rpx;

    .label {
      display: block;
      font-size: 30rpx;
      color: #2c3e50;
      margin-bottom: 16rpx;
      font-weight: 600;
    }

    .input {
      width: 100%;
      height: 88rpx;
      border: 2rpx solid #e8eaed;
      border-radius: 16rpx;
      padding: 0 24rpx;
      font-size: 30rpx;
      background: #fff;
      box-sizing: border-box;
      transition: all 0.3s ease;

      &:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 6rpx rgba(102, 126, 234, 0.1);
        outline: none;
      }

      &::placeholder {
        color: #999;
        font-size: 28rpx;
      }
    }
  }

  .login-btn {
    width: 100%;
    height: 96rpx;
    background: #667eea;
    color: #fff;
    border: none;
    border-radius: 16rpx;
    font-size: 34rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.4);
    }

    &[loading] {
      opacity: 0.8;
      transform: none;
    }

    .btn-text {
      font-size: 34rpx;
      font-weight: 600;
    }
  }

  .back-to-wechat {
    margin-top: 40rpx;
    text-align: left;

    .back-link {
      color: #667eea;
      font-size: 28rpx;
      cursor: pointer;

      &:hover {
        opacity: 0.8;
      }

      &:active {
        opacity: 0.6;
      }
    }
  }

  .privacy-tips {
    margin-top: 40rpx;
    text-align: center;
    font-size: 24rpx;
    line-height: 1.6;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;

    .tips-text {
      color: #7f8c8d;
      margin: 0 4rpx;
    }

    .link-text {
      color: #667eea;
      text-decoration: underline;
      margin: 0 4rpx;
    }
  }
</style>
